﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Xml;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;

namespace AIMLbot4Glider_Updater
{
    public partial class Form1 : Form
    {
        //public event DownloadProgressChangedEventHandler DownloadProgressChanged;
        string BaseDir = AppDomain.CurrentDomain.BaseDirectory;

        string url = "http://aimbot.webhop.net/AIMLbot4Glider.dll";   
        string filename = "AIMLbot4Glider.dll";
        string FullPath;

        string HelpURL = "http://aimbot.webhop.net/aimlbot help.chm";
        string Helpfilename = "aimlbot help.chm";
        string HelpFullPath;

        public Form1()
        {
            InitializeComponent();
        }

        public bool isLocked(string s)
        {
            if (!File.Exists(s)) return false;
            try { FileStream f = File.Open(s, FileMode.Open, FileAccess.ReadWrite); f.Close(); }
            catch { return true; }
            return false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            FullPath = BaseDir.Substring(0, BaseDir.IndexOf("Classes")) + filename;
            HelpFullPath = BaseDir + Helpfilename;

            if (!File.Exists(FullPath))
            {
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult result;

                result = MessageBox.Show(this, "Can't find the " + filename + " file to update !" + FullPath, "Updater", buttons, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                this.Close();
            }

            Thread Wait = new Thread(new ThreadStart(WaitForUnlock));
            Wait.Start();

            this.Text = HelpFullPath;
        }

        private void WaitForUnlock()
        {
            while (isLocked(FullPath))
            {
                toolStripStatusLabel1.Text = "File is locked (By glider, close it) ?";
                Thread.Sleep(500);
            }
            toolStripStatusLabel1.Text = "Ready to proceed";
            label2.Visible = false;
            GetCurrent();
        }

        private void Downloader()
        {
            try
            {
                toolStripStatusLabel1.Text = "Downloading files";
                WebClient client = new WebClient();
                Uri uri = new Uri(url);

                // Specify that the DownloadFileCallback method gets called
                // when the download completes.
                client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleated);
                // Specify a progress notification handler.
                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                client.DownloadFileAsync(uri, FullPath);

                WebClient client2 = new WebClient();
                Uri uri2 = new Uri(HelpURL);
                client2.DownloadFileAsync(uri, HelpFullPath);                

            }
            catch (WebException exc)
            {
                toolStripStatusLabel1.Text = exc.Message.ToString();
            }
            catch (UriFormatException exc)
            {
                toolStripStatusLabel1.Text = exc.Message.ToString();
            }
        }


        public void GetCurrent()                                         // Check internet for latest version
        {
            XmlTextReader reader;
            try
            {
                reader = new XmlTextReader("http://aimbot.webhop.net/Current.xml");

                string CurrentElementName = "";
                string DouwnloadURL = "";
                bool CoreOnly = false;

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Element: // The node is an element.
                            CurrentElementName = reader.Name;
                            break;

                        case XmlNodeType.Text: //Display the text in each element.
                            if (CurrentElementName == "URL") DouwnloadURL = reader.Value;
                            if (CurrentElementName == "CoreOnly")
                            {
                                if (reader.Value == "True") CoreOnly = true;
                            }
                            if (CurrentElementName == "Number")
                            {
                                if (CoreOnly)
                                {
                                    Downloader();
                                }
                                else
                                {
                                    MessageBoxButtons buttons = MessageBoxButtons.YesNo;
                                    DialogResult result;

                                    result = MessageBox.Show(this, "This update cannot be downloaded automatically. Would you go and download it manually?", "Updater", buttons, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                                    if (result == DialogResult.Yes)
                                    {
                                        System.Diagnostics.Process.Start(DouwnloadURL);
                                        this.Close();
                                    }
                                    else this.Close();
                                }
                            }
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                this.toolStripStatusLabel1.Text = e.Message;
            }
        }

        private void DownloadCompleated(object sender, AsyncCompletedEventArgs e)
        {
            button2.Enabled = true;
            toolStripStatusLabel1.Text = "Done";
            
        }

        private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            this.toolStripStatusLabel1.Text = (string)e.UserState;
            this.progressBar1.Value =  e.ProgressPercentage;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label2.Visible = false;
            progressBar1.Visible = true;
            GetCurrent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

    }
}
